package dao

import (
	"douyin/model"
	"douyin/utils/cache"
	"errors"
	"strconv"
	"sync"

	"gorm.io/gorm"
)

type commentDAO struct{}

var (
	commentDaoInstance *commentDAO
	commentOnce        sync.Once
)

// NewComment 单例模式创建 commentDAO
func NewComment() *commentDAO {
	commentOnce.Do(func() {
		commentDaoInstance = &commentDAO{}
	})
	return commentDaoInstance
}

// Add 增加评论的操作， c 里面只包含userID、videoID、content三项内容
func (*commentDAO) Add(c *model.Comment) error {
	err := db.Model(&model.Comment{}).
		Create(c).
		Error
	return err
}

// Delete 删除评论，只需提供 commentID 即可
func (*commentDAO) Delete(id int64) error {
	err := db.Model(&model.Comment{}).Delete(&model.Comment{}, 10).Error
	return err
}

func (*commentDAO) List(videoID int64) ([]model.Comment, error) {
	var c []model.Comment
	err := db.Model(&model.Comment{}).
		Select([]string{"id", "content", "user_id", "create_at"}).
		Where("video_id = ?", videoID).
		Find(&c).Error

	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}

	return c, nil
}

// QueryCommentCountByCache 从缓存中加载评论数量
func (*commentDAO) QueryCommentCountByCache(videoID int64) int64 {
	if c, ok := cacheGroup["comment"]; ok {
		b, err := c.Get(strconv.FormatInt(videoID, 10))
		if err != nil {
			return 0
		}
		return cache.BytesToInt64(b.ByteSlice())
	}
	return 0
}

// 更新缓存里面的评论数量
func updateCommentCountByCache(videoID int64, count int64) {
	if c, ok := cacheGroup["comment"]; ok {
		c.Set(strconv.FormatInt(videoID, 10), cache.Int64ToBytes(count))
	}
}

// IncreaseCommentCountByCache 更新缓存里面的值
func (*commentDAO) IncreaseCommentCountByCache(videoID int64, delta int64) {
	count := NewComment().QueryCommentCountByCache(videoID)
	updateCommentCountByCache(videoID, count+delta)
}

func (*commentDAO) DecreaseCommentCountByCache(videoID int64, delta int64) {
	count := NewComment().QueryCommentCountByCache(videoID)
	updateCommentCountByCache(videoID, count-delta)
}
